package com.srwl.mytx.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;

import androidx.annotation.NonNull;

import com.srwl.easeui.utils.EaseUtils;
import com.srwl.mytx.EaseConstant;
import com.srwl.mytx.R;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.fragment.ChatFragment;
import com.srwl.mytx.im.IMSClientBootstrap;
import com.srwl.mytx.im.conversation.Conversation;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.SoftKeyboardFixerForFullscreen;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.List;


public class ChatActivity extends BaseActivity implements PermissionsUtils.IPermissionsResult {
    public static void startActivity(Context context, User targetUser) {
        context.startActivity(new Intent(context, ChatActivity.class).putExtra(EaseConstant.EXTRA_TARGET_USER_INFO, targetUser));
    }

    public static ChatActivity activityInstance;
    private ChatFragment chatFragment;
    private String toChatUserId;
    private Conversation conversation;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            finish();
        }
        setContentView(R.layout.em_activity_chat);
        activityInstance = this;
        //get user id or group id
        User targetUser = getIntent().getParcelableExtra(EaseConstant.EXTRA_TARGET_USER_INFO);
        if (targetUser != null) {
            toChatUserId = targetUser.getuId();
        }
        conversation = IMSClientBootstrap.getInstance().getConversationService().getC2cConversation(toChatUserId);
        chatFragment = new ChatFragment();
        chatFragment.setArguments(getIntent().getExtras());
        getSupportFragmentManager().beginTransaction().add(R.id.container_layout, chatFragment).commit();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        activityInstance = null;
        PermissionsUtils.getInstance().clear();
        //删除 临时联系人
    }

    @Override
    protected void onResume() {
        super.onResume();
        conversation.setActivityInBackstage(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        conversation.setActivityInBackstage(true);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // make sure only one chat activity is opened
        User targetUser = getIntent().getParcelableExtra(EaseConstant.EXTRA_TARGET_USER_INFO);
        if (targetUser == null) {
            return;
        }
        String username = targetUser.getuId();
        if (TextUtils.equals(toChatUserId, username))
            super.onNewIntent(intent);
        else {
            finish();
            startActivity(intent);
        }

    }

    @Override
    public void onBackPressed() {
        chatFragment.onBackPressed();
        if (EaseUtils.isSingleActivity(this)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
        }
    }

    public String getToChatUserId() {
        return toChatUserId;
    }


//    @Override
//    public void back(View view) {
//        DeleteTemporaryContanct();
//    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_HEADSETHOOK) {
            Log.d("耳机按键down：", keyCode + "   " + event.getEventTime() + "");
            chatFragment.onMediaButtonKeyEvent(keyCode, event);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onStart() {
        super.onStart();
        String[] permissions;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        } else {
            permissions = new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        }
        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {
        chatFragment.refreshMessageList();
    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(ChatActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    //    private void DeleteTemporaryContanct() {
//
//        if (!bol_isMyFriend){
//            DemoHelper.getInstance().deleteContanctInMemory(chatTargetId);
//        }
//        finish();
//    }


}
